<template>

  <el-upload :action="baseURL+'api/File'"
             ref="upload"
             :accept="accept"
             :limit="limit"
             :on-success="SuccessFile"
             :before-remove="RemoveFile"
             :on-exceed="UpExceed"
             :before-upload="BeforeUpImage"
             :on-preview="onPreview"
             :headers="{'AuthToken':token}"
             name="Files"
             :data="upData"
             :file-list="inList"
             :list-type="listType">
    <div slot="trigger"
         :class="{H:inList.length>=limit&&listType!='picture-card'}">
      <el-button size="small"
                 :class="{H:inList.length>=limit&&listType!='picture-card'}"
                 type="primary">点击上传</el-button>
    </div>

    <div slot="tip"
         class="tip">{{tip}}</div>
  </el-upload>
</template>
<script>
import API from '../../../api/index';//读入restfulAPI
import MainTool from '../../../utils/MainTool';
import { mapState, mapMutations } from "vuex";
export default {
  name: 'customUpload',
  props: {
    accept: String,
    limit: Number,
    listType: String,
    tip: String,
    fileList: {
      type: Array,
      default: ()=>{
        return []
      }
    },
    onPreview: {
      type: Function,
      default: ()=>{
        
      }
    },
  },
  data () {
    return {
      upData: {},
      inList:this.fileList,
    };
  },
  created () {

  },
  watch: {
    fileList (newValue) {
      this.inList = newValue
    }
  },
  computed: {
    ...mapState(["token", "baseURL"]),

  },
  methods: {
    Clear () {
      this.upData = {}
    },
    BeforeUpImage (file) {
      this.upData = { Name: file.name }
      return this.$nextTick()
    },
    UpExceed (files, fileList) {
      this.$message.warning(`当前限制选择 ${this.limit} 个文件，已经选择了 ${files.length + fileList.length} 个文件`);
    },
    SuccessFile (response, file, fileList) {
      let idlist = []
       let list = []
      fileList.map(it => {
        if (it.status == "success") {
          it.urlid = it.response.detail.id
          it.url = MainTool.FileIdToUrl(it.urlid)
          idlist.push(it.urlid)
          list.push(it)
        }
      })
      this.inList = fileList
      this.$emit('update:filelist', fileList)
      this.$emit('update:idlist', idlist)
    },
    RemoveFile (file, fileList) {
      let idlist = []
      let list = []
      fileList.map(it => {
        if (it.status == "success" && it.response.detail.id != file.response.detail.id) {
          idlist.push(it.response.detail.id)
          list.push(it)
        }
      })
      this.inList = fileList
      this.$emit('update:filelist', fileList)
      this.$emit('update:idlist', idlist)
    },

  }
};
</script>

<style scoped>
.H {
    visibility: hidden;
    height: 0;
    width: 0;
    padding: 0;
    margin: 0;
    border: 0;
}
</style>